﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace CommonHelper
{
    public static class CMDHelper
    {
        /// <summary>
        /// 执行CMD命令
        /// </summary>
        /// <param name="commond">要执行的命令</param>
        /// <param name="outputResult">是否输出执行命令的输出结果</param>
        /// <returns></returns>
        public static string RunCMD(string commond, bool outputResult=true)
        {
            StringBuilder builder = new StringBuilder();

            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";

            //执行命令
            process.StartInfo.Arguments = "/c " + commond;

            process.StartInfo.UseShellExecute = false;//不启用shell
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;//不使用窗口
            process.Start();
            if (outputResult)
            {
                StreamReader reader = process.StandardOutput;
                string line = "";//每次读取一行
                while ((line = reader.ReadLine()) != null)
                {
                    builder.AppendLine(line);
                }
                reader.Close();
            }

            process.WaitForExit();
            process.Close();

            return builder.ToString();
        }
    }
}
